package com.bootcamp.inventory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import atg.commerce.order.CommerceItem;
import atg.commerce.order.Order;
import atg.core.util.StringUtils;
import atg.nucleus.logging.ApplicationLoggingImpl;
import atg.service.pipeline.PipelineProcessor;
import atg.service.pipeline.PipelineResult;

public class ProcCheckInventory extends ApplicationLoggingImpl implements PipelineProcessor {
	private InventoryErrorChecker	mInventoryErrorCheckerService;



	public int[] getRetCodes() {
		return new int[] { 1,STOP_CHAIN_EXECUTION_AND_ROLLBACK};
	}



	public int runProcess(Object pParam, PipelineResult pResult) throws Exception {
		HashMap map = (HashMap)pParam;
        Order order = (Order)map.get("Order");
        List items = order.getCommerceItems();
        for (Iterator iterator = items.iterator(); iterator.hasNext();) {
        	CommerceItem item = (CommerceItem) iterator.next();
        	String productId = item.getAuxiliaryData().getProductId();
        	String skuId = item.getCatalogRefId();
        	long quantity = item.getQuantity();
        	String checkResult = getInventoryErrorCheckerService().checkInventory(productId, skuId, (int) quantity);
        	if(!StringUtils.isEmpty(checkResult)){
        		pResult.addError(productId + "," + skuId, checkResult);
        	}
		}
        
        if(pResult.hasErrors()){
        	return STOP_CHAIN_EXECUTION_AND_ROLLBACK;
        }        
        return 1;
	}



	public InventoryErrorChecker getInventoryErrorCheckerService() {
		return mInventoryErrorCheckerService;
	}



	public void setInventoryErrorCheckerService(InventoryErrorChecker mInventorychErrorCheckerService) {
		this.mInventoryErrorCheckerService = mInventorychErrorCheckerService;
	}

}
